from permissionapp.models import Permission, Invitation
from django.contrib.auth.models import User
from django.core.mail import EmailMessage

def set_permission(emails, timeline):    
    for u in emails:
        try:
            user=User.objects.get(username=u)
            permission = Permission(user=user, timeline=timeline)
            permission.save()
        except:
            store_invitation(u, timeline)
        
def send_invitation(emails, timeline):
    subject, from_email = 'Crowd Timeline - Convite', 'crowdtimeline@gmail.com'
    html_content = '<p>Voce foi convidado para editar uma Timeline privada. Para comecar a editar a Timeline, acesse o link a seguir:</p><a href=\'http://127.0.0.1:8000/timelines/%s\'>Timeline</a>' % timeline.id
    msg = EmailMessage(subject, html_content, from_email, emails)
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
    
def store_invitation(email, timeline):
    try:
        user = User.objects.get(username=email)
    except User.DoesNotExist:
        invitation = Invitation(timeline=timeline, email=email)
        invitation.save()
        
def check_invitations(user):
    invitations = Invitation.objects.filter(email=user.username)
    
    for i in invitations:
        emails = []
        emails.append(i.email)
        set_permission(emails,i.timeline)
    

    